/**
 * Copyright 2011, Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.appengine.codelab;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;

/**
 * This servlet responds to the request corresponding to User Story 17. 
 * 
 * @author
 */
@SuppressWarnings("serial")
public class UserStory17Servlet extends BaseServlet {

	private static final Logger logger = Logger
			.getLogger(UserStory17Servlet.class.getCanonicalName());

	/**
	 * Searches for the entity based on the search criteria and returns result
	 * in JSON format
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		logger.log(Level.INFO, "Obtaining Query listing");
		String searchBy = req.getParameter("us17-searchby");
		String searchFor = req.getParameter("q");
		PrintWriter out = resp.getWriter();
		if (searchFor == null || searchFor.equals("")) {
			Iterable<Entity> entities = Fraude.getAllFraudes();
			out.println(Util.writeJSON(entities));
		} else if (searchBy == null || searchBy.equals("trans_id")) {
			Iterable<Entity> entities = Transacao.getTransacao(searchFor);
			out.println(Util.writeJSON(entities));
		} else if (searchBy.equals("consulta1")) {
			Iterable<Entity> entities = Fraude.getFraude(searchFor);
			out.println(Util.writeJSON(entities));
		} else if (searchBy.equals("consulta2")) {
			Iterable<Entity> entities = this.getTransacaoForAFraudeType("ESTELIONATO");
			out.println(Util.writeJSON(entities));
		} else if (searchBy.equals("consulta3")) {
			Iterable<Entity> entities = this.getFraudesForEstabelecimento("NETSHOES");
			out.println(Util.writeJSON(entities));
		} else if (searchBy.equals("consulta4")) {
			Iterable<Entity> entities = this.getLocalidadesForAFraudeType("ESTELIONATO");
			out.println(Util.writeJSON(entities));
		} else {
			logger.log(Level.INFO, "Invalid search by: us17-searchby=" + searchBy);
		}
	}

	public Iterable<Entity> getTransacaoForAFraudeType(String tipoFraude){
		ArrayList<Entity> list = new ArrayList<Entity>();
		Iterable<Entity> entities = Util.listEntities("Fraude","fraude_type",tipoFraude);
		for (Entity entity:entities)
		{
			String transId = entity.getProperty("trans_id").toString();
			Entity transacao = Transacao.getSingleTransacao(transId);
			list.add(transacao);
		}
		return list;
	}

	public Iterable<Entity> getFraudesForEstabelecimento(String estabelecimentoNome){
		ArrayList<Entity> list = new ArrayList<Entity>();
		Entity estabelecimento = Estabelecimento.getSingleEstabelecimento(estabelecimentoNome);
		Iterable<Entity> entitiesTransacao = Util.listEntities("Transacao",null,null);
		for (Entity entity:entitiesTransacao)
		{
			String estabelecimento_id = estabelecimento.getProperty("estabelecimento_id").toString();
			String estabelecimentoTransacaoId = entity.getProperty("estabelecimento_id").toString();
			if (estabelecimento_id.equals(estabelecimentoTransacaoId))
			{
				String transId = entity.getProperty("trans_id").toString();
				Iterable<Entity> entitiesFraude = Util.listEntities("Fraude","trans_id",transId);
				for (Entity entityFraude:entitiesFraude)
				{
					list.add(entityFraude);
				}
			}
		}
		return list;
	}
	
	public Iterable<Entity> getLocalidadesForAFraudeType(String tipoFraude){
		ArrayList<Entity> list = new ArrayList<Entity>();
		Iterable<Entity> entities = Util.listEntities("Fraude","fraude_type",tipoFraude);
		for (Entity entity:entities)
		{
			String transId = entity.getProperty("trans_id").toString();
			Entity transacao = Transacao.getSingleTransacao(transId);
			String localidadeId = transacao.getProperty("localidade_id").toString();
			Entity localidade = Localidade.getSingleLocalidade(localidadeId);
			list.add(localidade);
		}
		return list;
	}


}